﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Duellum.Core;
using JpLabs.Geometry;
using Duellum.Wpf2d.Plugin.Drawing;

namespace Duellum.Wpf2d.Plugin
{
    public class MapCursorRenderer : BaseMapSingleRenderer
    {
		private readonly int visualZOrder;

		private IDrawing2D drawing;
		private readonly TrackableValue<PointInt?> position = new TrackableValue<PointInt?>();
		
		public MapCursorRenderer(IDrawing2D drawing, int visualZOrder)
		{
			this.visualZOrder = visualZOrder;
			this.drawing = drawing;
			
			position.ValueChanged += Position_Changed;
		}

		protected override int VisualZOrder
		{
			get { return visualZOrder; }
		}

		public PointInt? Position
		{
			get { return position.Value; }
			set { position.Value = value; }
		}

		public double Rotation
		{
			get; set;
		}

		public event EventHandler<ValueChangedEventArgs<PointInt?>> PositionChanged
		{
			add		{ position.ValueChanged += value; }
			remove	{ position.ValueChanged -= value; }
		}
		
		private void Position_Changed(object sender, ValueChangedEventArgs<PointInt?> e)
		{
			OnRender();
		}

		public IDrawing2D Drawing
		{
			get { return drawing; }
			set {
				drawing = value;
				OnDrawingChanged();
			}
		}

		protected virtual void OnDrawingChanged()
		{
			OnRender();
		}
		
		public override void OnRender()
		{
			this.Drawing.Render(this.Visual, this.Position, this.Rotation);
		}
	}

    public class MapMouseCursorRenderer : MapCursorRenderer
    {
		public MapMouseCursorRenderer(MapCursorDrawing cursorDrawing, int visualZOrder)
			: base(cursorDrawing, visualZOrder)
		{}
		
		protected override void  OnAttachVisualParent(UIElement visualParent)
		{
 			base.OnAttachVisualParent(visualParent);
			
			this.VisualHost.MouseLeave	+= VisualHost_MouseLeave;
			this.VisualHost.MouseMove	+= VisualHost_MouseMove;
		}
		
		protected override void  OnDetachVisualParent(UIElement visualParent)
		{
 			base.OnDetachVisualParent(visualParent);
			
			this.VisualHost.MouseLeave	-= VisualHost_MouseLeave;
			this.VisualHost.MouseMove	-= VisualHost_MouseMove;
		}

		private void VisualHost_MouseMove(object sender, MouseEventArgs e)
		{
			var position = Wpf2dPlugin.PointToPosition(e.GetPosition((IInputElement)sender));
			
			this.Position = position;
		}

		private void VisualHost_MouseLeave(object sender, MouseEventArgs e)
		{
			this.Position = null;
		}
	}
}
